package org.jix.weblog.module.common.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.jix.weblog.module.common.config.MinioProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @version 1.0
 * @Author Jix
 * @Date 2024/9/7 11:03
 * @注释
 */

@Component
@Slf4j
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception {
        //判断文件是否为空
        if (file == null || file.getSize() == 0) {
            log.error("怎么？要我上传你那项上人头？");
            throw new RuntimeException("空的，狗屁不是！");
        }
        //文件原始名
        String originalFilename = file.getOriginalFilename();
        //文件的content-type
        String contentType = file.getContentType();
        //生存存储对象的名称
        String key = UUID.randomUUID().toString().replace("-", "");
        //文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接文件名
        String objectName = String.format(key, suffix);
        log.info("......让我看看......嗯，ObjectName: {}", objectName);
        //上传文件至minio
        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(contentType)
                        .build());
        //返回访问链接
        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
        log.info("好了，它在: {}",url);
        return url;
    }
}
